// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::{btree_map, BTreeMap};

use serde::{Deserialize, Serialize};

use crate::{Version, VersionReq};

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DepsConfig(pub BTreeMap<String, PkgDepConfig>);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PkgDepConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub default: Version,
    pub req: VersionReq,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub optional: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recursive: Option<bool>,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DepsConfigError {
    #[error("the default version of '{0}' is not matched with its req")]
    DefaultVersionNotMatch(String),
}

impl DepsConfig {
    pub fn new() -> Self {
        Self(BTreeMap::new())
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn contains(&self, name: &String) -> bool {
        self.0.contains_key(name)
    }

    pub fn iter(&self) -> btree_map::Iter<'_, String, PkgDepConfig> {
        self.0.iter()
    }

    pub fn iter_mut(&mut self) -> btree_map::IterMut<'_, String, PkgDepConfig> {
        self.0.iter_mut()
    }

    pub fn non_optional_deps(&self) -> impl Iterator<Item = (&String, &PkgDepConfig)> {
        self.0.iter().filter(|(_, config)| !config.optional)
    }

    pub fn verify(&self) -> Result<(), DepsConfigError> {
        for (name, config) in self.iter() {
            if !config.verify() {
                return Err(DepsConfigError::DefaultVersionNotMatch(name.clone()));
            }
        }
        Ok(())
    }
}

impl PkgDepConfig {
    pub fn verify(&self) -> bool {
        self.req.matches(&self.default)
    }
}

impl FromIterator<(String, PkgDepConfig)> for DepsConfig {
    fn from_iter<T: IntoIterator<Item = (String, PkgDepConfig)>>(iter: T) -> Self {
        Self(BTreeMap::from_iter(iter))
    }
}

#[cfg(test)]
mod test {
    use crate::{config::{dep_config::PkgDepConfig, DepsConfig}, Version, VersionOp, VersionReq};

    #[test]
    fn test_pkg_dep_config_serialize() {
        let mut s = String::new();
        serde::Serialize::serialize(
            &PkgDepConfig {
                name: None,
                default: Version::from_standard(1, 2, 3),
                req: VersionReq::new(VersionOp::Greater, Version::from_standard(1, 2, 3)),
                features: Vec::new(),
                optional: false,
                recursive: None,
            },
            toml::ser::ValueSerializer::new(&mut s)
        ).unwrap();
        assert_eq!(
            &s,
            "{ default = \"1.2.3\", req = \">1.2.3\" }"
        );

        s.clear();
        serde::Serialize::serialize(
            &PkgDepConfig {
                name: None,
                default: Version::from_major(1),
                req: VersionReq::new(VersionOp::Greater, Version::from_major(1)),
                features: vec!["feature1".to_string(), "feature2".to_string()],
                optional: true,
                recursive: None,
            },
            toml::ser::ValueSerializer::new(&mut s)
        ).unwrap();
        assert_eq!(
            &s,
            "{ default = \"1\", req = \">1\", features = [\"feature1\", \"feature2\"], optional = true }"
        );
    }

    #[test]
    fn test_pkg_dep_config_deserialize() {
        assert_eq!(
            &format!("{}", toml::from_str::<PkgDepConfig>("default = \"$\"\n").unwrap_err()),
            "TOML parse error at line 1, column 11\n  \
               |\n\
             1 | default = \"$\"\n  \
               |           ^^^\n\
               bad major number\n"
        );
        assert_eq!(
            toml::from_str("default = \"1\"\nreq = \"*\""),
            Ok(PkgDepConfig {
                name: None,
                default: Version::from_major(1),
                req: VersionReq::all(),
                features: vec![],
                optional: false,
                recursive: None,
            })
        );
        assert_eq!(
            toml::from_str("\
                default = \"1.2.3\"\n\
                req = \">1.1\"\n\
                features = [\"test\"]\n\
                optional = true\n\
                recursive = false\n"),
            Ok(PkgDepConfig {
                name: None,
                default: Version::from_standard(1, 2, 3),
                req: VersionReq::new(VersionOp::Greater, Version::from_standard(1, 1, 0)),
                features: vec!["test".to_string()],
                optional: true,
                recursive: Some(false),
            })
        );
    }

    #[test]
    fn test_deps_config_serialize() {
        let config = DepsConfig([
            (
                "pkg1".to_string(),
                PkgDepConfig {
                    name: None,
                    default: Version::from_major(1),
                    req: VersionReq::all(),
                    features: vec![],
                    optional: false,
                    recursive: None,
                }
            ),
            (
                "pkg2".to_string(),
                PkgDepConfig {
                    name: None,
                    default: Version::from_major(2),
                    req: VersionReq::new(VersionOp::Greater, Version::from_major(1)),
                    features: vec!["f1".to_string(), "f2".to_string()],
                    optional: true,
                    recursive: None,
                }
            )
        ].into_iter().collect());

        assert_eq!(
            toml::to_string(&config).unwrap(),
            "[pkg1]\n\
             default = \"1\"\n\
             req = \"*\"\n\
             \n\
             [pkg2]\n\
             default = \"2\"\n\
             req = \">1\"\n\
             features = [\"f1\", \"f2\"]\n\
             optional = true\n".to_string()
        );
    }

    #[test]
    fn test_requirements_config_deserialize() {
        let config = DepsConfig([
            (
                "pkg1".to_string(),
                PkgDepConfig {
                    name: None,
                    default: Version::from_major(1),
                    req: VersionReq::all(),
                    features: vec![],
                    optional: false,
                    recursive: None,
                }
            ),
            (
                "pkg2".to_string(),
                PkgDepConfig {
                    name: None,
                    default: Version::from_major(2),
                    req: VersionReq::new(VersionOp::Greater, Version::from_major(1)),
                    features: vec!["f1".to_string(), "f2".to_string()],
                    optional: true,
                    recursive: None,
                }
            )
        ].into_iter().collect());
        assert_eq!(
            toml::from_str("\
                [pkg1]\n\
                default = \"1\"\n\
                req = \"*\"\n\
                \n\
                [pkg2]\n\
                default = \"2\"\n\
                req = \">1\"\n\
                features = [\"f1\", \"f2\"]\n\
                optional = true\n"
            ),
            Ok(config)
        )
    }
}